﻿using System;
using System.Collections.Generic;
using System.Data;

namespace Finance.Data.Entities
{
	internal class DocumentProductCollection : DataBaseObjectCollection<IDocumentProduct>
	{
		private readonly Document _parentDocument;

		private const string DocumentProductsQuery =
			"select documentproduct.*, product.name  from documentproduct" +
			" left join product on product.productid = documentproduct.productid" +
			" where documentproduct.documentid = @p0";

		private const string DocumentProductUpdateQuery =
			"update documentproduct set amount = @p0, price = @p1, totalprice = @p2, productid = @p3, discount = @p4 where documentproductid = @p5";

		private const string DocumentProductInsert = 
			"insert into documentproduct (documentproductid, amount, price, totalprice, productid, documentid, discount) values (@p0, @p1, @p2, @p3, @p4, @p5, @p6)";

		public DocumentProductCollection(DataBase dataBase, Document parentDocument)
			: base(dataBase, "documentproduct")
		{
			_parentDocument = parentDocument;
		}

		protected override void Update(IDocumentProduct item)
		{
			var productId = ((FinanceDataBase)DataBase).Products.GetOrCreateProduct(item.ProductName);

			DataBase.Sql.ExecuteNonQuery(DocumentProductUpdateQuery, item.Amount, item.Price, item.TotalPrice, productId, item.Discount, item.Id);
		}

		
		protected override void Insert(IDocumentProduct item)
		{
			item.Id = Guid.NewGuid();
			
			var productId = ((FinanceDataBase)DataBase).Products.GetOrCreateProduct(item.ProductName);

			DataBase.Sql.ExecuteNonQuery(DocumentProductInsert, 
				item.Id,
				item.Amount, 
				item.Price, 
				item.TotalPrice, 
				productId, 
				_parentDocument.Id,
				item.Discount);
		}

		public override IDocumentProduct NewItem()
		{
			return new DocumentProduct(this);
		}

		public override void Save(object item)
		{
			Save((DocumentProduct)item);
		}

		public void GetDocumentProducts(IList<IDocumentProduct> targetList)
		{
			if(_parentDocument.Id == Guid.Empty)
				throw new Exception("Parent document did not saved");

			using (var reader = DataBase.Sql.ExecuteReader(DocumentProductsQuery, _parentDocument.Id))
			{
				while (reader.Read())
				{
					targetList.Add(ParseItem(reader));
				}
			}
		}

		protected override IDocumentProduct ParseItem(IDataRecord reader)
		{
			return new DocumentProduct(this) {
					Amount = (decimal) reader["amount"],
					Id = (Guid) reader["documentproductid"],
					Price = (decimal) reader["price"],
					TotalPrice = (decimal) reader["totalprice"],
					ProductName = (string) reader["name"],
					Discount = reader["discount"] != DBNull.Value ? (decimal) reader["discount"] : 0m
				};
		}
	}
}
